package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.KhPayConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.khpay.ebank.KhPayMessage;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 平安跨行支付订单查询类
 * 
 * @CheckOrderKhPayImpl.java
 * @author zhengxue
 * @2017-8-17 下午5:18:49 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderKhPayImpl implements BankOrderService {
    private Logger logger = Logger.getLogger("KHPAY");
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;

    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String arg1) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());
        KhPayMessage message = new KhPayMessage();
        message.setOrderId(bankOrder.getOrderId()); // 国付宝系统订单号
        message.setBankOrderId(bankOrder.getOutOrderId());
        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
        message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
        message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(), "yyyyMMddHHmmss"));
        message.setBank(bankOrder.getBankCode());

        Result result = new Result();
        try {
            if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
                message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
                result = bankClient.refundQuery(message);
                return refundCheckOrder(result, bankOrder);
            } else {
                result = bankClient.query(message);
            }

            if (result == null || !result.isSuccess()) {
                logger.error("bankClient fail.");
                if (result == null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())) {
                    BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                    checkOrderResult.setCommunicateError(true);
                }
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("系统返回对账结果为空");
                return checkOrderResult;
            }

            KhPayMessage res = (KhPayMessage) result.getDefaultModel();
            if (res == null) {
                // 查询结果为空
                logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
                        + ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
                checkOrderResult.setErrMsg("银行返回对账结果为空");
                return checkOrderResult;
            }

            String errorCode = res.getErrorCode(); // 错误码
            String errorMsg = res.getErrorMsg(); // 错误信息
            String status = res.getStatus(); // 订单状态
            // 成功处理
            if (KhPayConstants.STATUS_SUCCESS.equals(status)) {
                checkOrderResult.setSuccess(true);
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(bankOrder.getOrderId());
                accInfo.setAmount(res.getAmount());
                accInfo.setRetCode("00");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                logger.info("平安跨行支付订单：" + bankOrder.getOrderId() + "的交易成功" + "返回码：" + status);
            } else {
                checkOrderResult.setErrMsg("银行返回交易状态不明");
                logger.info("平安跨行支付订单：" + bankOrder.getOrderId() + "查询失败" + "错误码：" + errorCode + "错误信息：" + errorMsg);
            }
            return checkOrderResult;
        } catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("银行对账异常");
            return checkOrderResult;
        }
    }

    // 退款返回处理
    public CheckOrderResult refundCheckOrder(Result result, BankOrder bankOrder) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        if (result == null || !result.isSuccess()) {
            logger.error("refund bankClient fail.");
            if (result == null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())) {
                BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                checkOrderResult.setCommunicateError(true);
            }
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("系统返回退款对账结果为空");
            return checkOrderResult;
        }

        KhPayMessage res = (KhPayMessage) result.getDefaultModel();
        if (res == null) {
            // 退款查询结果为空
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E6022
                    + " err:bis query is null.");
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("银行返回退款对账结果为空");
            return checkOrderResult;
        }

        String errorCode = res.getErrorCode(); // 错误码
        String errorMsg = res.getErrorMsg(); // 错误信息
        String status = res.getRefundStatus(); // 退款状态
        if (KhPayConstants.REFUND_STATUS_SUCCESS.equals(status)) {
            // 成功处理
            checkOrderResult.setSuccess(true);
            InAccInfo accInfo = new InAccInfo();
            accInfo.setOrderId(bankOrder.getOrderId());
            accInfo.setAmount(new BigDecimal(res.getRefundAmt()));
            accInfo.setRetCode("00");
            accInfo.setCardType(BankCardType.Unknown.toString());
            checkOrderResult.setAccInfo(accInfo);
            logger.info("平安跨行退款订单：" + bankOrder.getOrderId() + "的交易成功" + "返回码：" + status);
        } else if (KhPayConstants.REFUND_STATUS_FAIL.equals(status)) {
            // 失败处理
            checkOrderResult.setBankFailure(true);
            InAccInfo accInfo = new InAccInfo();
            accInfo.setOrderId(bankOrder.getOrderId());
            accInfo.setAmount(new BigDecimal(res.getRefundAmt()));
            accInfo.setRetCode("01");
            accInfo.setCardType(BankCardType.Unknown.toString());
            checkOrderResult.setAccInfo(accInfo);
            logger.info("平安跨行退款订单：" + bankOrder.getOrderId() + "的交易失败" + "返回码：" + status);
        } else if (KhPayConstants.REFUND_STATUS_DEALING.equals(status)) {
            // 处理中
            checkOrderResult.setErrMsg("银行返回退款交易处理中");
            logger.info("平安跨行退款订单：" + bankOrder.getOrderId() + "的交易失败" + "返回码：" + status);
        } else {
            if ("EBKPY004".equals(errorCode)) {
                // 纪录不存在
                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
                checkOrderResult.setErrMsg(errorCode);
            } else {
                checkOrderResult.setErrMsg("银行返回退款交易状态不明");
            }
            logger.info("平安跨行退款订单：" + bankOrder.getOrderId() + "查询失败" + "错误码：" + errorCode + "错误信息：" + errorMsg);
        }
        return checkOrderResult;
    }

    @Override
    public BankOrder getDbOrder() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BaseMessage dayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<CheckOrderResult> checkDayend(String bank_bus) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result getDayendMsg(String string) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
        // TODO Auto-generated method stub
        return null;
    }
}
